import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { taskEntity } from "@/drizzle/model/taskEntity";
import { and, asc, desc, eq, gte, InferSelectModel, lt, ne } from "drizzle-orm";
import { database } from "@/drizzle";
import { startOfDay, endOfDay } from "date-fns";
// 通过类型推断反射得到 taskEntity 模型中字段的类型和值类型
type TaskSelect = Omit<InferSelectModel<typeof taskEntity>, "createdAt"> & {
  createdAt?: number; // 允许 createdAt 为 number 类型
};

const list = createAsyncThunk<TaskSelect[], Slice.IItemTaskTimerSlice>("taskItem/list", async ({ date }) => {
  
  const targetDateStart = startOfDay(new Date(date)); // 当天开始时间
  const targetDateEnd = endOfDay(new Date(date)); // 当天结束时间

  const query = database
    .select()
    .from(taskEntity)
    .where(and(eq(taskEntity.isDeleted, false), gte(taskEntity.createdAt, targetDateStart), lt(taskEntity.createdAt, targetDateEnd)))
    .orderBy(asc(taskEntity.status), desc(taskEntity.createdAt));
  const tasks = await query;

  return tasks.map(task => ({
    ...task,
    createdAt: task.createdAt ? task.createdAt.getTime() : 0, // 转换为时间戳
  }));
});

const taskItemSlice = createSlice({
  name: "taskItem",
  initialState: [] as TaskSelect[],
  reducers: {},
  extraReducers: builder => {
    builder.addCase(list.fulfilled, (state, action) => {
      state = action.payload;
      return state;
    });
  },
});

export { list as listTaskItem, TaskSelect, taskItemSlice };
